//
//  CYSBDetail.m
//  CreditAddressBook
//
//  Created by mosu on 2016/11/4.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYSBDetail.h"
#import "CYUser.h"
#import "CYHttpTool.h"
#import "CYLoginHttpTool.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "CYDES3Util.h"
#import "MBProgressHUD+LE.h"
#import "UIAlertView+Block.h"
#import <ZMCreditSDK/ALCreditService.h>
#import "DCPaymentView.h"
#import "AddressView.h"

@interface CYSBDetail ()<UIAlertViewDelegate,UIPickerViewDelegate,UIWebViewDelegate>
@property (nonatomic, strong)UIWebView *webview;
@property (weak, nonatomic) IBOutlet UITextField *usernameTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UITextField *areaAddressTF;


@property (nonatomic, strong) UIToolbar *toolBar;
@property (nonatomic, strong) UIPickerView *picker;
@property (nonatomic, strong) NSArray *pickdata;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) UITextField *dealTF;
@end

@implementation CYSBDetail

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = CYColor(147, 197, 83, 1);
     _passwordTF.secureTextEntry = YES;
    [self loadareaData];
    // Do any additional setup after loading the view from its nib.
}

-(void)loadareaData{
     
     [CYHttpTool postWithURL:[CYURL shared].getSecurityArea params:nil success:^(id json) {
          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
          if (jsoninfo.isSuccess) {
               _picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.height/1.5,self.view.width,self.view.height/3 )];
               //    指定Delegate
               _picker.delegate=self;
               _dataArray = jsoninfo.data;
               _pickdata=_dataArray;
               _picker.showsSelectionIndicator=YES;
               _areaAddressTF.inputView = self.picker;
               _areaAddressTF.inputAccessoryView = self.toolBar;
               
          }
          
     } failure:^(NSError *error) {
          
     }];
     
}

//返回显示的列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
     return 1;
}
//返回当前列显示的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
     return [_pickdata count];
}

#pragma mark Picker Delegate Methods

//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
     return [_pickdata objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
     _areaAddressTF.text = _pickdata[row];
     
}
- (UIToolbar *)toolBar{
     if (_toolBar == nil) {
          self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
          _toolBar.barTintColor= CYColor(103, 190, 102, 1);
          
          UIBarButtonItem *item1=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
          //        UIBarButtonItem *item2=[[UIBarButtonItem alloc]initWithTitle:@"请选择银行" style:UIBarButtonItemStylePlain target:self action:nil];
          UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(confirm)];
          _toolBar.items = @[item1, item2];
     }
     return _toolBar;
}
- (void)confirm {
     if ([_areaAddressTF.text isEqualToString:@""]) {
          self.areaAddressTF.text = _dataArray[0];
     }
     [self.areaAddressTF resignFirstResponder];
}

- (IBAction)submitClick:(id)sender {
     if (_usernameTF.text.length == 0) {
          CYAlertView(@"请输入社保账号");
          return;
     }
     if (_passwordTF.text.length== 0) {
          CYAlertView(@"请输入社保密码");
          return;
     }
     if (_areaAddressTF.text.length == 0) {
          CYAlertView(@"请选择社保缴纳所在地区");
          return;
     }
     DCPaymentView *payAlert = [[DCPaymentView alloc]init];
     payAlert.detail = @"请输入交易密码";
     [payAlert show];
     payAlert.completeHandle = ^(NSString *inputPwd) {
          NSString *desstr = [CYDES3Util encrypt:inputPwd];
          CYUser *user = [CYLoginHttpTool userData].user;
          
          _webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, [[UIScreen mainScreen ]bounds].size.width,[[UIScreen mainScreen ]bounds].size.height)];
          _webview.backgroundColor =CYColor(147, 197, 83, 1);
          _webview.delegate = self;
          if (user) {
               [[self navigationController] setNavigationBarHidden:YES animated:NO];
               //http://192.168.0.172:8058   http://www.credit-manage.com:8058
               NSString *urlstr = [NSString stringWithFormat:@"http://www.credit-manage.com:8058/phone/juhe/saveJuHeSecurity.htm?userId=%@&token=%@&username=%@&password=%@&dealCode=%@&area=%@",user.userId,user.token,_usernameTF.text,_passwordTF.text,desstr,_areaAddressTF.text];
               NSString *strUrl = [urlstr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
               NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
               [_webview loadRequest:request];
               [self.view addSubview:_webview];
          }
          
          
//          [CYHttpTool postWithURL:[CYURL shared].saveJuHeSecurityFirst params:@{@"userId":user.userId,@"token":user.token,@"username":_usernameTF.text,@"password":_passwordTF.text,@"area":_areaAddressTF.text,@"dealCode":desstr} success:^(id json) {
//               CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
//               //
//               [MBProgressHUD hideHUDForView:self.view animated:YES];
//               NSString *data = jsoninfo.data;
//               if (data && data.intValue == 0) {
//                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入您所获取到的验证码" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//                    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
//                    [alert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
//                         if (buttonIndex == 1) {
//                              _dealTF = [alert textFieldAtIndex:0];
//                              [CYHttpTool postWithURL:[CYURL shared].saveJuHeSecuritySecond params:@{@"userId":user.userId,@"token":user.token,@"smsCode":_dealTF.text} success:^(id json) {
//                                   [MBProgressHUD hideHUDForView:self.view animated:YES];
//                                   CYJsonInfo *jsoninfo1 = [CYJsonInfo objectWithKeyValues:json];
//                                   CYAlertView(jsoninfo1.message);
//                                   [self.navigationController popViewControllerAnimated:YES];
//                                   
//                              } failure:^(NSError *error) {
//                                   [MBProgressHUD hideHUDForView:self.view animated:YES];
//                              }];
//                              
//                         }
//                    }];
//                    
//               }else{
//                    CYAlertView(jsoninfo.message);
//                    [self.navigationController popViewControllerAnimated:YES];
//                    [MBProgressHUD hideHUDForView:self.view animated:YES];
//                    
//               }
//               
//          } failure:^(NSError *error) {
//               [MBProgressHUD hideHUDForView:self.view animated:YES];
//               
//          }];
          
     };
     
}

#pragma mark -
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
     [alert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
          if (buttonIndex == 0) {
               [[self navigationController] setNavigationBarHidden:NO animated:NO];
               [self.navigationController popViewControllerAnimated:YES];
               
          }
     }];
     
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
     //[self.view addSubview:_hiview];
     //[MBProgressHUD hideHUDForView:self.view];
     NSString *url = [[request URL] absoluteString];
     NSLog(@"url = %@",url);
     //h5内返回控件字段方法:loanlist
     if([url hasSuffix:@"loanlist"]) {
          dispatch_async(dispatch_get_main_queue(), ^{
               //返回上一级时，取消nav的隐藏
               [[self navigationController] setNavigationBarHidden:NO animated:NO];
               [self dismissViewControllerAnimated:YES completion:^{
                    //do what you want
                    
               }];
               //js交互oc获取到h5内的返回按钮后，点击返回，popvc
               [self.navigationController popViewControllerAnimated:YES];
          });
          return NO;
     }
     
     return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
